const { Address } = require("../models/appUser");

// Create a new address
createAddress = async (req, res) => {
  try {
    const appUserId = req.userId; // 获取用户ID
    const { isDefault } = req.body;

    // 如果新地址设置为默认地址，检查是否已有默认地址
    if (isDefault) {
      const defaultAddress = await Address.findOne({
        where: { appUserId, isDefault: true },
      });
      if (defaultAddress) {
        // 如果已有默认地址，将其设置为非默认地址
        await defaultAddress.update({ isDefault: false });
      }
    }

    const address = await Address.create({ ...req.body, appUserId });

    res.status(200).json({
      code: 200,
      message: "添加成功",
      data: address,
    });
    return;
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

getAllAddresses = async (req, res) => {
  try {
    const appUserId = req.userId; // 获取用户ID
    await Address.findAll({
      where: {
        appUserId,
      },
    }).then((addresses) => {
      res.json({
        code: 200,
        message: "获取成功",
        data: addresses,
      });
    });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// Get a single address by ID
getAddressById = async (req, res) => {
  try {
    const appUserId = req.userId; // 获取用户ID
    Address.findOne({
      where: {
        id: req.params.id,
        appUserId,
      },
    }).then((address) => {
      res.json({
        code: 200,
        message: "获取成功",
        data: address,
      });
    });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// Update an address by ID
updateAddress = async (req, res) => {
  try {
    const appUserId = req.userId; // 获取用户ID
    let { isDefault } = req.body;
    if (!isDefault) {
      isDefault = false;
    }
    const address = await Address.findOne({
      where: {
        id: req.params.id,
        appUserId,
      },
    });

    if (address) {
      // 如果更新后的地址设置为默认地址，检查是否已有默认地址
      if (isDefault) {
        const defaultAddress = await Address.findOne({
          where: { appUserId, isDefault: true, id: { [Op.ne]: req.params.id } },
        });
        if (defaultAddress) {
          return res.status(400).json({ error: "每个用户只能有一个默认地址" });
        }
      }

      let data = await address.update(req.body);
      // 返回更新成功提示
      res.json({
        code: 200,
        message: "更新成功",
        data: data,
      });
    } else {
      res.status(404).json({ error: "Address not found" });
    }
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// Delete an address by ID
deleteAddress = async (req, res) => {
  try {
    const appUserId = req.userId; // 获取用户ID
    const address = await Address.findOne({
      where: {
        id: req.params.id,
        appUserId,
      },
    });
    if (address) {
      let data = await address.destroy();
      // 返回删除成功提示
      res.json({
        code: 200,
        message: "删除成功",
        data: data,
      });
    } else {
      res.status(404).json({ error: "Address not found" });
    }
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

module.exports = {
  createAddress,
  getAllAddresses,
  getAddressById,
  updateAddress,
  deleteAddress,
};
